﻿// 
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2011
// by DotNetNuke Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.


using System;

using DotNetNuke;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using System.Globalization;
using Triax.Modules.ThongKeATLD;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Triax.Modules.Department;

namespace Triax.Modules.CSDLAnhHien
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditCSDLAnhHien class is used to manage content
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// </history>
    /// -----------------------------------------------------------------------------
    partial class EditCSDLAnhHien : PortalModuleBase
    {

    #region Private Members

        private int ItemId = Null.NullInteger;
        int level = -1;
    #endregion

    #region Event Handlers

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void Page_Load(System.Object sender, System.EventArgs e)
        {
            try
            {
              
             // this.Control.Visible = false;

                //If this is the first visit to the page, bind the role data to the datalist
                if (Page.IsPostBack == false)
                {
                    getDonViHanhChinh();
                    getTinhThanh();
                    if (this.Request.QueryString["act"] == "Delete")
                    {
                        Response.Write("Ddelete id1 = ");
                        if (this.Request.QueryString["ItemId"] != null)
                        {
                            try
                            {
                                int ItemId = Int32.Parse(this.Request.QueryString["ItemId"]);
                                DepartmentController ctr = new DepartmentController();
                                ctr.DeleteDonViTapDoan(this.ModuleId, ItemId);
                                //  Response.Write("Ddelete id = " + ItemId);
                                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                            }
                            catch (Exception ee)
                            {
                                Response.Write(ee.Message);

                                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                            }

                        }
                    }
                    //Determine ItemId of CSDLAnhHien to Update
                    if (this.Request.QueryString["ItemId"] != null)
                    {
                        ItemId = Int32.Parse(this.Request.QueryString["ItemId"]);
                    }
                    cmdDelete.Attributes.Add("onClick", "javascript:return confirm('" + Localization.GetString("DeleteItem") + "');");

                    if(ItemId != -1)
                    {
                        //get content
                        DepartmentController objCSDLAnhHiens = new DepartmentController();
                        DonViTapDoanInfo objCSDLAnhHien = objCSDLAnhHiens.GetDonViTapDoan(ModuleId, ItemId);
                        if (objCSDLAnhHien != null)
                        {
                           // DateTime.Parse(txtEffectiveDate.Text);
                       //     Ngaythang.Text = String.Format("{0:dd/MM/yyyy}", objCSDLAnhHien.FDate1);

                            F1.Text = objCSDLAnhHien.code;
                            F2.Text = objCSDLAnhHien.title;
                            F3.Text = objCSDLAnhHien.Description;
                            ddlParent.SelectedValue = objCSDLAnhHien.ParentId.ToString();
                            tinhthanh.SelectedValue = objCSDLAnhHien.temp_int2.ToString();

                            ctlAudit.CreatedByUser = objCSDLAnhHien.CreatedByUser.ToString();
                            ctlAudit.CreatedDate = objCSDLAnhHien.CreatedDate.ToString();
                        }
                        else
                        {
                            Response.Redirect(Globals.NavigateURL(), true);
                        }
                    }
                    else
                    {
                       
                        cmdDelete.Visible = false;
                        ctlAudit.Visible = false;
                    }
                }
           }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdCancel_Click runs when the cancel button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdCancel_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdDelete_Click runs when the delete button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdDelete_Click(System.Object sender, System.EventArgs e)
        {
            try
            {
                //Only attempt to delete the item if it exists already
                if (!Null.IsNull(ItemId))
                {
                    DepartmentController objCSDLAnhHiens = new DepartmentController();
                    objCSDLAnhHiens.DeleteDonViTapDoan(ModuleId,ItemId);
 
                    //refresh cache
                    SynchronizeModule();
                }

                this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// cmdUpdate_Click runs when the update button is clicked
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void cmdUpdate_Click(System.Object sender, System.EventArgs e)
        {
            try

            {
                if (this.Request.QueryString["ItemId"] != null)
                {
                    ItemId = Int32.Parse(this.Request.QueryString["ItemId"]);
                }

                DepartmentController objCtr = new DepartmentController();
                DonViTapDoanInfo obj = new DonViTapDoanInfo();
                obj.ModuleId = this.ModuleId;
                obj.code = F1.Text;
                obj.title = F2.Text;
                obj.ParentId = int.Parse(ddlParent.SelectedValue);
                obj.temp_int2 = int.Parse(tinhthanh.SelectedValue);
                //tinhthanh.SelectedValue = objCSDLAnhHien.temp_int2.ToString();
                obj.Description = F3.Text;
                obj.temp_double1= 0;
                obj.temp_double2 = 0;
                obj.temp_string1 = "";
                obj.temp_string2 = "";
                obj.temp_string3= "";
                obj.temp_int1 =2; // Ngoài nước
               // obj.temp_int2=0; // Tỉnh
                obj.temp_int3=0;
                obj.CreatedByUser= this.UserId;
                obj.CreatedDate = DateTime.Now;
                obj.UpdatedByUser = this.UserId;
                obj.UpdatedDate =     DateTime.Now;
                

                //Update the content within the CSDLAnhHien table
                if (Null.IsNull(ItemId))
                {
                    string condCheck = " And Code Like N'" + obj.code + "'";
                    condCheck += " and temp_int1 =2 And title Like N'" + obj.title + "'";
                    List<DonViTapDoanInfo> ds = objCtr.GetDonViTapDoansByCond(0, condCheck, "");
                    if (ds != null && ds.Count > 0)
                    {
                        Error.Text = "Lỗi: Đơn vị đã tồn tại";
                    }
                    else
                    {
                        objCtr.AddDonViTapDoan(obj);
                        this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                    }
                }
                else
                {
                    obj.id = ItemId;
                    objCtr.UpdateDonViTapDoan(obj);
                    this.Response.Redirect(Globals.NavigateURL(this.TabId), true);
                }

                //refresh cache
                SynchronizeModule();

                //Redirect back to the portal home page
                
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }
        public string showvalue(string v)
        {
            string res = "";
            if (v == "-1")
                return "";

            res =Convert.ToSingle(v).ToString();
            return res;

        }

        protected void getTinhThanh()
        {
            ThongkeATLDController objCtr = new ThongkeATLDController();
            tinhthanh.Items.Clear();
            tinhthanh.AppendDataBoundItems = true;
            tinhthanh.Items.Insert(0, new ListItem("-----------", "0"));
            string condp = " and  temp_int1 =1 AND ParentID = 0";
            
            List<DonViHanhChinhInfo> p = objCtr.GetDonViHanhChinhsByCond(this.ModuleId, condp, "");
            tinhthanh.DataSource = p;
            tinhthanh.DataValueField = "id";
            tinhthanh.DataTextField = "title";
            tinhthanh.DataBind();
         //   RecursiveFillTree2(p, 0);

        }
        private void RecursiveFillTree2(List<DonViHanhChinhInfo> dtParent, int parentID)
        {
            ThongkeATLDController objCtr = new ThongkeATLDController();

            level += 1;
            //on the each call level increment 1
            StringBuilder appender = new StringBuilder();
            for (int j = 0; j <= level - 1; j++)
            {
                appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            if (level > 0)
            {
                appender.Append("|__");
            }
            //using (TNLDEntities data = new TNLDEntities()) 
            {
                //string cond = " AND ParentID = " + parentID.ToString();
                //List<DonViHanhChinhInfo> dv = objCtr.GetDonViHanhChinhsByCond(this.ModuleId, cond, "");
                //int i;

                //if (dv.Count > 0)
                //{
                //    for (i = 0; i <= dv.Count - 1; i++)
                //    {
                //        ListItem itm = new ListItem(Server.HtmlDecode(appender.ToString() + dv[i].code.ToString() + " - " + dv[i].title.ToString()), dv[i].id.ToString());
                //        itm.Attributes.Add("class", "ItemActived");
                //        tinhthanh.Items.Add(itm);
                //        RecursiveFillTree2(dtParent, int.Parse(dv[i].id.ToString()));
                //    }
                //}
            }
            level -= 1;
            //on the each function end level will decrement by 1
        }

        protected void getDonViHanhChinh()
{
    DepartmentController objCtr = new DepartmentController();
	ddlParent.Items.Clear();
	ddlParent.AppendDataBoundItems = true;
	ddlParent.Items.Insert(0, new ListItem("-----------", "0"));
    string condp = "  AND temp_int1 =2 AND ParentID = 0";
    List<DonViTapDoanInfo> p = objCtr.GetDonViTapDoansByCond(this.ModuleId, condp, "");
		ddlParent.DataValueField = "id";
		ddlParent.DataTextField = "title";
		RecursiveFillTree(p, 0);
	
}
        private void RecursiveFillTree(List<DonViTapDoanInfo> dtParent, int parentID)
{
    DepartmentController objCtr = new DepartmentController();
           
	level += 1;
	//on the each call level increment 1
	StringBuilder   appender = new StringBuilder();
	for (int j = 0; j <= level - 1; j++) {
		appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;");
	}
	if (level > 0) {
		appender.Append("|__");
	}
	//using (TNLDEntities data = new TNLDEntities()) 
    {
        string cond = " AND temp_int1 =2 AND ParentID = " + parentID.ToString();
        List<DonViTapDoanInfo> dv = objCtr.GetDonViTapDoansByCond(this.ModuleId, cond, "");
		int i;

		if (dv.Count > 0) {
			for (i = 0; i <= dv.Count - 1; i++) {
				ListItem itm = new ListItem(Server.HtmlDecode(appender.ToString() + dv[i].code.ToString() + " - " + dv[i].title.ToString()), dv[i].id.ToString());
				itm.Attributes.Add("class", "ItemActived");
				ddlParent.Items.Add(itm);
				RecursiveFillTree(dtParent,  int.Parse(dv[i].id.ToString()));
			}
		}
	}
	level -= 1;
	//on the each function end level will decrement by 1
}


    #endregion

        protected void update_Click(object sender, EventArgs e)
        {

        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            //string[] danhsach = new string[] {
               

            //ThongkeATLDController objCtr = new ThongkeATLDController();
            //List<DonViHanhChinhInfo> listTinhs = objCtr.GetDonViHanhChinhsByCond(0, " AND ParentId = 0 ", "");
            //for (int i = 0; i < danhsach.Length; i++)
            //{
            //    string[] data = danhsach[i].Split(',');
            //    DonViHanhChinhInfo obj = new DonViHanhChinhInfo();
            //    obj.ModuleId = this.ModuleId;
            //    obj.code = data[0];
            //    obj.title = data[1].Replace("'","''") ;
            //    //obj.ParentId = int.Parse(ddlParent.SelectedValue);
            //    obj.Description = "";
            //    obj.temp_double1 = 0;
            //    obj.temp_double2 = 0;
            //    obj.temp_string1 = "";
            //    obj.temp_string2 = "";
            //    obj.temp_string3 = "";
            //    obj.temp_int1 = 2;
            //    obj.temp_int2 = 0;
            //    obj.temp_int3 = 0;
            //    obj.CreatedByUser = this.UserId;
            //    obj.CreatedDate = DateTime.Now;
            //    obj.UpdatedByUser = this.UserId;
            //    obj.UpdatedDate = DateTime.Now;
                
            //    DonViHanhChinhInfo d1 = getDVHC(listTinhs, data[2]);
            //    if (d1 != null)
            //    {
            //        string cond = " AND code LIKE N'" + obj.code.Replace( "'", "''") + "' AND title Like N'" + obj.title + "' ";
            //        List<DonViHanhChinhInfo> check1 = objCtr.GetDonViHanhChinhsByCond(0, cond, "");
            //        if (check1 != null && check1.Count > 0)
            //        {
                        
            //        }
            //        else
            //        {
            //            obj.ParentId = d1.id;
            //            objCtr.AddDonViHanhChinh(obj);
            //            Response.Write("<br/> them: " + obj.code + " Titie " + obj.title); 
            //        }
            //    }
                
         //   }


        }


        public DonViHanhChinhInfo getDVHC(List<DonViHanhChinhInfo> listTinhs, string id)
        {
            for (int i = 0; i < listTinhs.Count; i++)
            {
                DonViHanhChinhInfo d = listTinhs[i];
                if (d.code.Equals(id))
                {
                    return d;
                }
            }
            return null;
        }
}
}

